﻿using System.IO;
using UFramework.Tools;
using System.Text;
public static class FileHelper
{
    /// <summary>
    /// 递归遍历文件夹中的所有文件,包括子文件夹,在根目录生成名为FileList.txt的文件列表
    /// </summary>
    public static void CreatFileListWithMD5(string root, string searchPattern = "*", string fileListName = "FileList.txt")
    {
        if (!root.EndsWith("\\") || !root.EndsWith("/"))
        {
            root = root + '/';
        }
        //避免大量字符串拼接浪费内存
        StringBuilder sb = new StringBuilder();
        //获取所有的文件
        string[] files = Directory.GetFiles(root, searchPattern, SearchOption.AllDirectories);
        for (int i = 0; i < files.Length; i++)
        {
            string f = files[i];
            if (f.EndsWith(fileListName))
            {
                continue;//跳过生成的列表文件
            }
            //拿到md5值
            string md5 = CaculateMd5.GetMD5FromFile(f);

            //拿到相对于root的路径
            string fileName = f.Replace(root, "");

            //拼接
            sb.Append(fileName);
            sb.Append("\t");
            sb.Append(md5);
            sb.Append("\n");
            string witePath = Path.Combine(root, fileListName);
            File.WriteAllText(witePath, sb.ToString());
        }
    }

    /// <summary>
    /// 检查完整路径中的文件夹是否存在,不存在就创建
    /// </summary>
    /// <param name="writePath"></param>
    public static void CreatDirBeforeWrite(string writePath)
    {
        string dir = Path.GetDirectoryName(writePath);
        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
    }
}